package com.carrie.config;

import com.carrie.tools.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
 * @author XuHaiLong
 * @since 2025/4/3
 */
@Configuration
public class DatabaseConnectionChecker implements CommandLineRunner {
    @Autowired
    private DataSource dataSource;
    @Override
    public void run(String... args) throws Exception {
        // 验证连接
        try (Connection connection = dataSource.getConnection()) {
            LogUtils.info("成功连接到数据库: " + connection.getCatalog());
        } catch (SQLException e) {
            LogUtils.error("数据库连接失败: " + e.getLocalizedMessage(), e);
            throw new RuntimeException("服务启动终止");
        }
    }
/*
    private final DruidDataSource druidDataSource;
    public DatabaseConnectionChecker(){
      this.druidDataSource = new DruidDataSource();
  }
    @Override
    public void run(String... args) throws Exception {
        // 打印连接池基础信息
        LogUtils.info("Druid 连接池配置：");
        LogUtils.info("URL: " + druidDataSource.getUrl());
        LogUtils.info("Active connections: " + druidDataSource.getActiveCount());
        LogUtils.info("Pooling count: " + druidDataSource.getPoolingCount());

        // 验证连接
        try (Connection connection = druidDataSource.getConnection()) {
            LogUtils.info("成功连接到数据库: " + connection.getCatalog());
            LogUtils.info("Druid 监控统计已启用，访问 http://localhost:8080/druid/index.html");
        } catch (SQLException e) {
            LogUtils.error("数据库连接失败: " + e.getLocalizedMessage(), e);
            throw new RuntimeException("服务启动终止");
        }
    }
*/
}